<?php
require_once("taskView.php");
require_once(CORE_DIR.'taskModel.php');
require_once(CORE_DIR.'projectModel.php');
require_once(CORE_DIR.'userModel.php');
require_once(CORE_DIR.'yammerModel.php');
require_once(CORE_DIR.'pointtypeModel.php');
require_once(CORE_DIR.'taskpointModel.php');

class updatestatusAction extends authAction
{
	const NINJA_TASK_COMPLETE_TITLE = "TASK IS COMPLETE: ";
	
	function __construct(){
		$this->view = new taskView();
	}

	public function run($get, $post, $viewtype) {
		parent::run($get,$post,$viewtype);
		
		$tModel = new taskModel();		
		
		if (isset($get["id"])){
			$id = $get["id"];
			$pid = $get["pid"];
			$tskStatus = $get["state"];
			
			$taskOldStatus = $tModel->getTaskDto($id)->getStatus();
			$status = 0;
			if (isset($tskStatus) && $tModel->updateTaskStatus($id,$pid,$tskStatus)){
				if($tskStatus == 1)
				{
					$tModel->notifyTasksOwnersLastTask($id);
				}
				$status = 1;
				
				$uModel = new userModel();
				$users = $uModel->getUsersList();
				$usersFbIds = array();
				foreach ($users as $user) {
					if (isset($user["fbuid"]) && $user["fbuid"] != "") {
						$usersFbIds[] = $user["fbuid"];
					}
				}
				$usersFbIds = implode(",", $usersFbIds);
				
////////////////////////////////////////Yammer///////////////////////////////////////////////				
				if($status == 1 && $taskOldStatus == 0)
				{
					$yModel = new yammerModel();
					$uModel = new userModel();
					$ptModel = new pointtypeModel();
					$tpModel = new taskpointModel();
					
					$activeUser = $uModel->getActiveUser();
					$taskOwner = $tModel->getOwner($id);
					
					
					if ( $yModel->isYammerActive($taskOwner->getId()) && $tskStatus != 0 )
					{
						$yammerDto = $yModel->getYammerData($taskOwner->getId());
						
						$task = $tModel->getTask($id);
						$prjName = $tModel->getTasksProjectName($id);
						
						$taskPointDtos = $tpModel->getTaskPointByTaskId($id);
						$taskPointMsg = array();
						foreach ($taskPointDtos as $taskPointDto)
						{
							$pointType = $ptModel->getPointTypesById($taskPointDto->getPointTypeId());
							$taskPointMsg[] = $taskPointDto->getPoint()." ".strtoupper($pointType[0]->getTypeName());
						}
						
						$taskPointMsg = implode(",", $taskPointMsg);
						
						$taskName = urldecode(htmlspecialchars_decode($task['name'], ENT_QUOTES));
						
			            $message = "[".$prjName." +".$taskPointMsg."] ". $taskName."\nTopics: #".$prjName;
			            					
						$result = $yModel->sendMessageToYammer($yammerDto->getOAuthToken(), $yammerDto->getOAuthTokenSecret(), $yammerDto->getOAuthVerifier(), $message);
					}
				}
////////////////////////////////////////Yammer///////////////////////////////////////////////				
			
			}
			$this->view->setProperty("status", $status);
			$this->view->setProperty("id", $id);
			$this->view->setProperty("usersFbIds", $usersFbIds);
			$this->view->showUpdateTask();
		}
		else{
			$this->view->showBadCmd();
		}	
			
	}
}
?>